//
//  OmniFocusConduit.m
//  Task Views
//
//  Created by Chris Karr on 3/25/09.
//  Copyright 2009 Audacious Software. All rights reserved.
//

#import "OmniFocusConduit.h"
#import "KFAppleScriptHandlerAdditionsCore.h"
#import "KFASHandlerAdditions-TypeTranslation.h"

@implementation OmniFocusConduit

- (NSString *) identifier
{
	return @"id";
}

- (NSArray *) fetchTasks:(NSDictionary *) options
{
	if ([[NSWorkspace sharedWorkspace] fullPathForApplication:@"OmniFocus"] == nil)
	{
		NSRunAlertPanel(@"Unable to find application", @"OmniFocus cannot be found on the local system.", @"OK", nil, nil);
		return [NSArray array];
	}

	NSBundle * bundle = [NSBundle mainBundle];
	
	NSString * script = [bundle pathForResource:@"OmniFocus" ofType:@"scpt" inDirectory:@"Conduits/omnifocus_conduit"];
	
	NSMutableArray * tasks = [NSMutableArray array];
	
	NSDictionary * error = nil;
	NSAppleScript * as = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:script] error:&error];
	
	if (script != nil)
	{
		NSAppleEventDescriptor * descriptor = [as executeAndReturnError:&error];
		
		id list = [descriptor objCObjectValue];
		
		if ([list isKindOfClass:[NSArray class]])
		{
			NSEnumerator * listIter = [list objectEnumerator];
			id value = nil;
			while (value = [listIter nextObject])
			{
				if ([value isKindOfClass:[NSDictionary class]])
				{
					NSMutableDictionary * task = [NSMutableDictionary dictionaryWithDictionary:value];
					[task setValue:@"OmniFocus" forKey:@"source"];

					for (id key in [task allKeys])
					{
						id value = [task valueForKey:key];
						
						if ([value isKindOfClass:[NSAppleEventDescriptor class]])
							[task removeObjectForKey:key];
					}
					
					[tasks addObject:task];
				}
			}
		}
	}
	else
	{
		// Check error
	}
	
	[as release];
	
	return tasks;
}

- (void) openExternalSite:(NSDictionary *) options
{
	[[NSWorkspace sharedWorkspace] launchApplication:@"OmniFocus"];
}

@end
